/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-11-24 22:42:13
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.risk.controller;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.risk.EvaluationPlanStrategies;
import com.joysuch.wwyt.risk.bean.*;
import com.joysuch.wwyt.risk.entity.RiskEvaluationControl;
import com.joysuch.wwyt.risk.entity.RiskEvaluationPlan;
import com.joysuch.wwyt.risk.entity.RiskPoint;
import com.joysuch.wwyt.risk.repository.RiskEvaluationControlDao;
import com.joysuch.wwyt.risk.repository.RiskEvaluationPlanDao;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.service.RiskEvaluationPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;

@RestController
@RequestMapping("/risk/evaluation-plan")
@Api(tags = "双预防-风险评估计划")
public class RiskEvaluationPlanController {

    private static final Logger logger = LoggerFactory.getLogger(RiskEvaluationPlanController.class);
    @Autowired
    private RiskEvaluationPlanDao dao;
    @Autowired
    private RiskPointDao pointDao;
    @Autowired
    private RiskEvaluationPlanService riskEvaluationPlanService;
    @Value("${wwyt.base.serverUrl}")
    private String serverUrl;
    @Autowired
    private RiskEvaluationControlDao riskEvaluationControlDao;

    @RequestMapping("add")
    public Object add(@Valid RiskEvaluationPlan entity) {
        try {
            riskEvaluationPlanService.add(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("创建失败", e);
            return ResultBean.fail(101, "创建失败");
        }
    }

    @RequestMapping("update")
    public Object update(@Valid RiskEvaluationPlan entity) {
        try {
            if (entity.getId() == null) {
                return ResultBean.fail(102, "未指定主键");
            }
            riskEvaluationPlanService.update(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("更新失败：#" + entity.getId(), e);
            return ResultBean.fail(101, "更新失败");
        }
    }

    // 控制风险评估计划列表
    @RequestMapping("control-risk-page")
    public Object page(Pageable page, RiskEvaluationPlanControlListSearchBean condition) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "createTime");
            Page<RiskEvaluationPlanControlListBean> data = riskEvaluationPlanService.findByPage(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    // 导出
    @RequestMapping("control-risk-list")
    public void SimpleWordExport(Pageable page) {
        Page<RiskPoint> all = pointDao.findAll(page);
        Map<String, Object> lm = new HashMap<String, Object>();
        List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
        // for (int i = 0; i < 4; i++) {
        for (RiskPoint riskPoint : all) {
            RiskEvaluationPlanControlListBean converts = converts(riskPoint);
            Map<String, String> map = new HashMap<String, String>();
            map.put("id", converts.getId() + "");
            map.put("code", converts.getCode());
            map.put("name", converts.getName());
            map.put("districtId", converts.getDistrictId() + "");
            map.put("districtName", converts.getDistrictName());
            map.put("type", converts.getType());
            map.put("riskLevel", converts.getRiskLevel() + "");
            map.put("riskLevelName", converts.getRiskLevelName());
            map.put("evaluationPlanId", converts.getEvaluationPlanId() + "");
            map.put("evaluationPeriodUnit", converts.getEvaluationPeriodUnit());
            map.put("evaluationPeriodName", converts.getEvaluationPeriodName());
            map.put("nextEvaluation", converts.getNextEvaluationDate());
            map.put("lastEvaluationDate", converts.getLastEvaluationDate());
            listMap.add(map);
        }
        lm.put("m", listMap);
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(
                    "D:/excel/风险控制.docx", lm);
            FileOutputStream fos = new FileOutputStream("D:/excel/风险控制数据.docx");
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private RiskEvaluationPlanControlListBean converts(RiskPoint f) {
        RiskEvaluationPlanControlListBean b = new RiskEvaluationPlanControlListBean();
        b.setId(f.getId());
        b.setName(f.getName());
        b.setCode(f.getCode());
        if (f.getRiskDistrict() != null) {
            b.setDistrictId(f.getRiskDistrict().getId());
            b.setDistrictName(f.getRiskDistrict().getName());
        }
        RiskEvaluationPlan plan = dao.findFirstByRiskPointId(f.getId(), Sort.by(Sort.Order.desc("createTime")));
        if (plan != null) {
            b.setEvaluationPeriod(plan.getPeriod());
            b.setEvaluationPeriodUnit(plan.getIntervalUnit());
            b.setEvaluationPlanId(plan.getId());
            b.setEvaluationPeriodName(EvaluationPlanStrategies.findNameByCode(plan.getStrategy()));
            if (plan.getNextEvaluationTime() != null) {
                b.setNextEvaluationDate(SimpleDateFormatCache.getYmd().format(plan.getNextEvaluationTime()));
            }
        }
        if (f.getLastEvaluationTime() != null) {
            b.setLastEvaluationDate(SimpleDateFormatCache.getYmd().format(f.getLastEvaluationTime()));
        }
        b.setRiskLevel(f.getRiskLevel());
        b.setRiskLevelName(RiskLevels.findRiskLevelName(f.getRiskLevel()));
        return b;
    }

    /**
     * Word文件页面显示
     *
     * @param res
     * @throws Exception
     */
    @RequestMapping("/openWord")
    public void openWord(HttpServletRequest request, HttpServletResponse res, Pageable page) throws Exception {
        // String path = request.getParameter("D:/excel/风险控制数据.docx");
        String path = URLDecoder.decode("D:/excel/风险控制数据.docx", "UTF-8");
        // byte[] bdata = fileToBytes("D:\\excel\\风险控制数据.xlsx");
        byte[] bdata = fileToBytes(path);
        if (bdata != null) {
            ServletOutputStream op;
            try {
                op = res.getOutputStream();
                op.write(bdata);
                op.close();
                if (op.equals(null)) {
                    res.flushBuffer();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * @param path
     * @return 变成IO流
     */
    @SuppressWarnings("resource")
    private byte[] fileToBytes(String path) {
        byte[] buffer = null;
        File file = new File(path);
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    // 打印
    @RequestMapping(value = "control-risk-print")
    public Object print(Pageable pageable, HttpServletRequest httpServletRequest) throws Exception {
        riskEvaluationPlanService.print(pageable);
        String retString = null;
        String dir = "D:/excel/test.pdf";
        retString = serverUrl + dir;
        return ResultBean.success(retString);
    }

    public static void showPdf(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("test/pdf");
        FileInputStream in = new FileInputStream(new File(fileName));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        while ((in.read(b)) != -1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }

    // 控制风险评估计划列表
    @RequestMapping("control-risk-batch-make-plan")
    public Object doControlRiskPlan(@Valid @Pattern(regexp = "(\\d{1,12},?)+", message = "必须是数字和逗号的组合") String ids,
                                    String strategy, Date evaluationTime, Integer versionFlag) {
        try {
            EvaluationPlanStrategies strategies = EvaluationPlanStrategies.findByCode(strategy);
            if (strategies == null) {
                return ResultBean.fail(103, "不支持的评估策略:" + strategy);
            }
            String[] ss = ids.split(",");
            List<Long> riskPointIdList = new ArrayList<>();
            for (String s : ss) {
                riskPointIdList.add(Long.parseLong(s));
            }
            riskEvaluationPlanService.batchMakePlan(riskPointIdList, strategies, evaluationTime, versionFlag);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    // 控制风险评估计划列表
    @RequestMapping("district-stable-risk-page")
    public Object districtStableRiskPage(Pageable page, RiskEvaluationPlanStableListSearchBean condition) {
        try {
            if (condition.getVersionFlag() != null && condition.getVersionFlag().intValue() == 1) {
                RiskEvaluationControl cor = riskEvaluationControlDao.findByName("控制风险评估");
                if (cor != null && cor.getSwitchState() != null && cor.getSwitchState() == 0) {
                    return ResultBean.success(new ArrayList<>());
                }
            }
            page = PageDataUtils.addOrderByDesc(page, "createTime");
            Page<RiskEvaluationPlanStableListBean> data = riskEvaluationPlanService.findDistrictStableRiskByPage(page,
                    condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    // 控制风险评估计划列表
    @RequestMapping("district-stable-risk-batch-make-plan")
    public Object doDistrictStableRiskPlan(
            @Valid @Pattern(regexp = "(\\d{1,12},?)+", message = "必须是数字和逗号的组合") String ids, String strategy,
            Date evaluationTime, Integer versionFlag) {
        try {
            EvaluationPlanStrategies strategies = EvaluationPlanStrategies.findByCode(strategy);
            if (strategies == null) {
                return ResultBean.fail(103, "不支持的评估策略:" + strategy);
            }
            String[] ss = ids.split(",");
            List<Long> riskPointIdList = new ArrayList<>();
            for (String s : ss) {
                riskPointIdList.add(Long.parseLong(s));
            }
            // 区域风险评估方案
            riskEvaluationPlanService.batchMakeDistrictStableRiskPlan(riskPointIdList, strategies, evaluationTime, versionFlag);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("deleteByRiskPointId")
    @RequiresPermissions("risk:plan:delete")
    public Object deleteByRiskPointId(Long riskPointId) {
        try {
            riskEvaluationPlanService.deleteByRiskPointId(riskPointId);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    @RequestMapping("delete")
    public Object delete(Long id) {
        try {
            riskEvaluationPlanService.delete(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    @PostMapping("remind-setting-save/{flag}")
    @ApiImplicitParam(name = "flag", value = "评估计划类型: 0 控制风险评估计划; 1 固有风险评估计划", paramType = "path", required = true)
    @ApiOperation("风险评估计划通知提醒配置-新增/修改")
    @RequiresPermissions("risk:evaluation-plan:remind-setting-save")
    public ResultBean remindSettingSave(@PathVariable Integer flag, @Valid @RequestBody RiskEvalPlanRemindBean bean) {
        return riskEvaluationPlanService.remindSettingSave(flag, bean);
    }

    @GetMapping("remind-setting-get/{flag}")
    @ApiImplicitParam(name = "flag", value = "评估计划类型: 0 控制风险评估计划; 1 固有风险评估计划", paramType = "path", required = true)
    @ApiOperation("风险评估计划通知提醒配置-查询")
    public ResultBean remindSettingGet(@PathVariable Integer flag) {
        return riskEvaluationPlanService.remindSettingGet(flag);
    }

}
